package com.muchfish.reactor.example;

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture<String> firstOperation = CompletableFuture.supplyAsync(() -> {
            try {
                // 模拟异步操作
                Thread.sleep(2000);
                return "First operation completed";
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        CompletableFuture<String> secondOperation = firstOperation.thenApplyAsync(result -> {
            System.out.println("First CompletableFuture: " + result);
            try {
                // 模拟异步操作
                Thread.sleep(2000);
                return "Second operation completed with input: " + result;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        CompletableFuture<String> thirdOperation = secondOperation.thenApplyAsync(result -> {
            System.out.println("Second CompletableFuture: " + result);
            try {
                // 模拟异步操作
                Thread.sleep(2000);
                return "Third operation completed with input: " + result;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        thirdOperation.whenComplete((result, throwable) -> {
            if (throwable == null) {
                System.out.println("Third CompletableFuture: " + result);
            } else {
                System.out.println("Error in CompletableFuture: " + throwable.getMessage());
            }
        });

        // 主线程继续执行其他操作
        System.out.println("Main thread continues...");

        // 等待所有操作完成
        CompletableFuture.allOf(firstOperation, secondOperation, thirdOperation).join();
    }
}

